#Requires AutoHotkey v2.0
#Include ../src/MapLib.ahk

Class BaseDynamicAddress {
  file := "E:\Desktop\obsidian\ahkFile\fileOpen\A_task.md" ;动态命令文件
  fileContent := this.getFile()  ;动态命令文件内容
  contentArr := this.init()       ;动态命令二维数组
  staticFileContent := this.fileContent        ;动态命令文件内容的静态比对变量

  getFile() {
    fileObject := FileOpen(this.file, "rw", "UTF-8")     ;创建file对象
    this.fileContent := fileObject.Read()        ;获取文本
    fileObject.Close()                  ;关闭文件
    return this.fileContent
  }

  init() {
    this.contentArr := StrSplit(this.fileContent,"`n-`s")     ;文本拆分成数组
    try {
      this.contentArr.RemoveAt(1)
    }
    for k in this.contentArr {
      this.contentArr[A_Index] := StrSplit(this.contentArr[A_Index],"`n`t-`s")   ;二维数组拆分
      PrefixMap[this.contentArr[A_Index][1]] := this.contentArr[A_Index][-1]     ;动态命令赋值
    }
    return this.contentArr
  }

  write(property) {
    replaced := 0         ;是否替换了现存命令的flag
    copy := A_Clipboard
    A_Clipboard := ""
    str := ""             ;写入文本
    if !(this.staticFileContent == this.getFile()) {
      this.init()
      this.staticFileContent := this.fileContent
    }
    Send "{Esc}{Esc}^l"
    Sleep 100
    Send "^c"
    if ClipWait(2) {
      PrefixMap[property] := A_Clipboard       ;动态命令赋值
      title := WinGetTitle("A")
      title := SubStr(title,1,InStr(title,"`s-`s",,-1))      ;命令的标注,这里选择浏览器标题
      for k in this.contentArr {
          if (k[1] = property) {               ;如果是现有命令则替换
              (k.Length > 2) or k.Length := 3
              k[2] := title        
              k[-1] := A_Clipboard
              replaced := 1
          }
          for i in k {
              if (A_Index = 1)
                  str .= "`n-`s" . i
              else
                  str .= "`n`t-`s" . i
          }
      }
      if !(replaced) {                          ;如果不是现有命令则追加
          this.contentArr.Length++
          this.contentArr[-1] := Array(property,title,A_Clipboard)
          str .= "`n-`s" . property . "`n`t-`s" . title . "`n`t-`s" . A_Clipboard
      }
      FileDelete(this.file)                  ;删除文件
      FileAppend(str,this.file, "UTF-8")     ;重新写入
      OnlyInput.fixedTip("dynamic adress`n" . title, 1500) 
    } else {
      OnlyInput.fixedTip("dynamic adress is invalid", 1500)
    }
    Send "{Esc}{Esc}"       
    A_Clipboard := copy
  }
}

DynamicAddress := BaseDynamicAddress()